package com.yzkj.cpjxc.business.service.impl;

import com.yzkj.cpjxc.business.domain.DictionaryConstants;
import com.yzkj.cpjxc.business.domain.Dickm;
import com.yzkj.cpjxc.business.domain.DickmQueryVo;
import com.yzkj.cpjxc.business.domain.DickmShowVo;
import com.yzkj.cpjxc.business.service.DickmService;
import com.yzkj.cpjxc.business.framework.common.BusinessMap;
import com.yzkj.cpjxc.business.framework.common.Constants;
import com.yzkj.cpjxc.business.framework.common.Pager;
import com.yzkj.cpjxc.business.framework.utils.IDUtils;
import com.yzkj.cpjxc.business.domain.ZhangTao;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 科目类别
 */
@Service
public class DickmServiceImpl implements DickmService {

	/**
	 * MyBatis 命名空间
	 */
	private final static String MAPPER_NAMESPACE = "com.chkj.dictionary.dickm.mappers.DickmMapper";

	@Autowired
	private SqlSessionTemplate sqlSessionTemplate;

	@Transactional
	@Override
	public BusinessMap create(Dickm dickm) throws Exception {
		BusinessMap bm = new BusinessMap();
		if (this.isExists(dickm)) {
//			bm.put(Constants.WARNING_MSG, "该科目类别名称(或代码)已经存在");
//			return bm;
		}
		dickm.setUuid(IDUtils.genUUID());

		Date date = new Date();
		dickm.setIsDelete(DictionaryConstants.DT_DELETE_ZC);
		dickm.setStatus(DictionaryConstants.DT_STATUS_QY);
		dickm.setCreateTime(date);
		dickm.setUpdateTime(date);

		// 编码中不能带有"-"字符
		if (StringUtils.isNotBlank(dickm.getDicCode()) && StringUtils.contains(dickm.getDicCode(), "-")) {
			bm.put(Constants.WARNING_MSG, "编码中不能带有横杠'-'字符");
			return bm;
		}

		// 设置层级id和层级code
		if (dickm != null) {

			String parentDicCode = dickm.getParentDicCode();
			String levelDicCode = dickm.getDicCode();
			String levelDicId = dickm.getUuid();

			String fullName = dickm.getDicName();
			int levelNum = 1;

			Dickm parent = null;
			if (!StringUtils.isBlank(parentDicCode)) {
				b: while (true) {
					parent = this.getByDicCode(parentDicCode);
					if (parent != null) {
						levelDicCode = parent.getDicCode() + "-" + levelDicCode;
						levelDicId = parent.getUuid() + "-" + levelDicId;
						fullName = parent.getDicName() + "-" + fullName;
						parentDicCode = parent.getParentDicCode();
						levelNum++;
					}
					if (parent == null || StringUtils.isBlank(parentDicCode)) {
						break b;
					}

					System.out.println("-----------科目类别循环提取设置层级id和层级科目编码---------------");
				}
			}
			dickm.setLevelDicCode(levelDicCode);
			dickm.setLevelDicId(levelDicId);
			dickm.setFullName(fullName);
			dickm.setLevelNum(levelNum + "");
		}

		sqlSessionTemplate.insert(MAPPER_NAMESPACE + ".add", dickm);
		return bm;
	}

	@Override
	public boolean isExists(Dickm dickm) throws Exception {
		return (Integer) sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".isExists", dickm) > 0;
	}

	@Override
	public Dickm getById(String dickmId) throws Exception {
		return sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".getById", dickmId);
	}

	@Transactional
	@Override
	public BusinessMap edit(Dickm dickm) throws Exception {

		Dickm yuanShiData = this.getById(dickm.getUuid());
		BusinessMap bm = new BusinessMap();

		if (this.isExists(dickm)) {
//			bm.put(Constants.WARNING_MSG, "该科目类别名称(或代码)已经存在");
//			return bm;
		}

		if (dickm.getDicCode().equals(dickm.getParentDicCode())) {
			bm.put(Constants.WARNING_MSG, "父级编码不能是自身的编码!");
			return bm;
		}

		Dickm parentTemp = this.getByDicCode(dickm.getParentDicCode());
		if (parentTemp == null) {
			if (StringUtils.isNotBlank(dickm.getParentDicCode())) {
				bm.put(Constants.WARNING_MSG, "请勿添加不存在的父级编码!");
				return bm;
			}
		} else {
			Map<String, String> map = new HashMap();
			map.put("yuanShiLevelDicId", yuanShiData.getLevelDicId());
			map.put("uuid", parentTemp.getUuid());
			if ((Integer) sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".isChild", map) > 0) {
				bm.put(Constants.WARNING_MSG, "不可以选择自己下属子编码为父级编码!");
				return bm;
			}
		}

		Date date = new Date();
		dickm.setIsDelete(DictionaryConstants.DT_DELETE_ZC);
		dickm.setUpdateTime(date);

		// 编码中不能带有"-"字符
		if (StringUtils.isNotBlank(dickm.getDicCode()) && StringUtils.contains(dickm.getDicCode(), "-")) {
			bm.put(Constants.WARNING_MSG, "编码中不能带有横杠'-'字符");
			return bm;
		}

		// 设置层级id和层级code
		if (dickm != null) {

			String parentDicCode = dickm.getParentDicCode();
			String levelDicCode = dickm.getDicCode();
			String levelDicId = dickm.getUuid();

			String fullName = dickm.getDicName();
			int levelNum = 1;

			Dickm parent = null;
			if (!StringUtils.isBlank(parentDicCode)) {
				b: while (true) {
					parent = this.getByDicCode(parentDicCode);
					if (parent != null) {
						levelDicCode = parent.getDicCode() + "-" + levelDicCode;
						levelDicId = parent.getUuid() + "-" + levelDicId;
						parentDicCode = parent.getParentDicCode();
						fullName = parent.getDicName() + "-" + fullName;
						levelNum++;
					}
					if (parent == null || StringUtils.isBlank(parentDicCode)) {
						break b;
					}

					System.out.println("-----------科目类别循环提取设置层级id和层级科目编码---------------");
				}
			}
			dickm.setLevelDicCode(levelDicCode);
			dickm.setLevelDicId(levelDicId);

			dickm.setFullName(fullName);
			dickm.setLevelNum(levelNum + "");
		}

		sqlSessionTemplate.update(MAPPER_NAMESPACE + ".edit", dickm);
		sqlSessionTemplate.flushStatements();

		// 判断如果科目类别代码有变化
		if (!yuanShiData.getDicCode().equals(dickm.getDicCode()) && StringUtils.isNotBlank(dickm.getDicCode())) {

			Map<String, String> map = new HashMap<String, String>();

			// 1.更新原始code的子数据的父级编码
			map.put("fileName", "PARENT_DIC_CODE");
			map.put("nowValue", dickm.getDicCode());
			map.put("yuanShiValue", yuanShiData.getDicCode());
			sqlSessionTemplate.update(MAPPER_NAMESPACE + ".editFileValue", map);

			// 2.更新LEVEL_DIC_CODE 分3中情况修改 避免充掉其他相近包含关系的CODE值 ,如QWER包含QWE,两个是不一样的CODE
			// 第一种
			map.put("nowValue", "-" + dickm.getDicCode());
			map.put("yuanShiValue", "-" + yuanShiData.getDicCode());
			map.put("condition", "%-" + yuanShiData.getDicCode());
			sqlSessionTemplate.update(MAPPER_NAMESPACE + ".editLevelDicCode", map);
			// 第二种
			map.put("nowValue", dickm.getDicCode() + "-");
			map.put("yuanShiValue", yuanShiData.getDicCode() + "-");
			map.put("condition", yuanShiData.getDicCode() + "-%");
			sqlSessionTemplate.update(MAPPER_NAMESPACE + ".editLevelDicCode", map);
			// 第三种
			map.put("nowValue", "-" + dickm.getDicCode() + "-");
			map.put("yuanShiValue", "-" + yuanShiData.getDicCode() + "-");
			map.put("condition", "%-" + yuanShiData.getDicCode() + "-%");
			sqlSessionTemplate.update(MAPPER_NAMESPACE + ".editLevelDicCode", map);

		}
		// 判断如果科目类别名称有变化
		if (!yuanShiData.getDicName().equals(dickm.getDicName()) && StringUtils.isNotBlank(dickm.getDicName())) {

			Map<String, String> map = new HashMap<String, String>();
			map.put("fileName", "PARENT_DIC_NAME");
			map.put("nowValue", dickm.getDicName());
			map.put("yuanShiValue", yuanShiData.getDicName());
			// 更新原始code的子数据的父级编码
			sqlSessionTemplate.update(MAPPER_NAMESPACE + ".editFileValue", map);

			Map<String, String> map2 = new HashMap<String, String>();
			map2.put("fileName", "FULL_NAME");
			map2.put("nowValue", dickm.getDicName());
			map2.put("yuanShiValue", yuanShiData.getDicName());
			map2.put("uuid", dickm.getUuid());
			// 更新所有匹配的全名成修改后的
			sqlSessionTemplate.update(MAPPER_NAMESPACE + ".editFileValue2", map2);
		}
		sqlSessionTemplate.flushStatements();
		return bm;
	}

	@Transactional
	@Override
	public boolean delete(String dickmId) throws Exception {
		sqlSessionTemplate.delete(MAPPER_NAMESPACE + ".deleteById", dickmId);
		return true;
	}

	@Override
	public Pager<DickmShowVo> search(Pager<DickmShowVo> pager, Dickm dickm) throws Exception {
		List<DickmShowVo> dataList = sqlSessionTemplate.selectList(MAPPER_NAMESPACE + ".page", dickm,
				new RowBounds((pager.getCurrentPage() - 1) * pager.getLimit(), pager.getLimit()));
		pager.setDataList(dataList);

		// 如果需要转换成ShowVo展示，那么就在这里转换

		Long total = sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".getTotal", dickm);
		pager.setTotal(total);
		return pager;
	}

	@Override
	public Map<String, String> getDictionaryMap() throws Exception {
		List<Dickm> dataList = sqlSessionTemplate.selectList(MAPPER_NAMESPACE + ".getDictionaryMap");
		Map<String, String> map = new LinkedHashMap<String, String>();
		if (dataList != null) {
			for (Dickm obj : dataList) {
				map.put(obj.getDicCode(), obj.getDicName());
			}
		}
		return map;
	}

	@Override
	public Dickm getByDicCode(String dicCode) throws Exception {
		if (StringUtils.isBlank(dicCode)) {
			return null;
		}
		return sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".getByDicCode", dicCode);
	}

	@Override
	public Map<String, String> getDictionaryMap2() throws Exception {
		List<Dickm> dataList = sqlSessionTemplate.selectList(MAPPER_NAMESPACE + ".getDictionaryMap2");
		Map<String, String> map = new LinkedHashMap<String, String>();
		if (dataList != null) {
			for (Dickm obj : dataList) {
				map.put(obj.getDicCode(), obj.getDicName());
			}
		}
		return map;
	}

	@Override
	public Map<String, String> getParentDicCodeIsNullMap() throws Exception {
		List<Dickm> dataList = sqlSessionTemplate.selectList(MAPPER_NAMESPACE + ".getParentDicCodeIsNull");
		Map<String, String> map = new LinkedHashMap<String, String>();
		if (dataList != null) {
			for (Dickm obj : dataList) {
				map.put(obj.getDicCode(), obj.getDicName());
			}
		}
		return map;
	}

	@Override
	public List<Dickm> getInitData() throws Exception {
		List<Dickm> dataList = sqlSessionTemplate.selectList(MAPPER_NAMESPACE + ".getDictionaryMap2");
		return dataList;
	}

	@Override
	public List<Dickm> getDictionaryList(Dickm dickm) throws Exception {
		List<Dickm> dataList = sqlSessionTemplate.selectList(MAPPER_NAMESPACE + ".getDictionaryList", dickm);
		return dataList;
	}

	@Override
	public List<Dickm> getByParentDicCode(Dickm dickm) throws Exception {
		List<Dickm> dataList = sqlSessionTemplate.selectList(MAPPER_NAMESPACE + ".getByParentDicCode", dickm);
		return dataList;
	}

	@Override
	public boolean isHavaChilds(String dicCode) throws Exception {
		return (Integer) sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".isHavaChilds", dicCode) > 0;
	}

	@Override
	public List<Dickm> getDickmByLikeCodeOrName(String dicCodeOrName) throws Exception {
		List<Dickm> dataList = sqlSessionTemplate.selectList(MAPPER_NAMESPACE + ".getDickmByLikeCodeOrName",
				dicCodeOrName);
		return dataList;
	}

	@Override
	public List<DickmShowVo> searchList(DickmQueryVo dickm) throws Exception {
		List<DickmShowVo> dataList = sqlSessionTemplate.selectList(MAPPER_NAMESPACE + ".searchList", dickm);
		return dataList;
	}

	@Override
	public BusinessMap createInitialFinancialbalance(List<DickmShowVo> pareList) throws Exception {
		BusinessMap bm = new BusinessMap();
		sqlSessionTemplate.insert(MAPPER_NAMESPACE + ".batchAdd", pareList);
		return bm;
	}

	@Override
	public boolean deleteInitialFinancialbalance(String zangTaoId, String currKeMuFenLei) throws Exception {
		if (StringUtils.isNotBlank(zangTaoId) && StringUtils.isNotBlank(currKeMuFenLei)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("zangTaoId", zangTaoId);
			map.put("currKeMuFenLei", currKeMuFenLei);
			sqlSessionTemplate.delete(MAPPER_NAMESPACE + ".deleteInitialFinancialbalance", map);
			return true;
		}
		return false;
	}

	@Override
	public DickmShowVo searchOne(DickmQueryVo qvo) throws Exception {
		DickmShowVo vo = sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".searchOne", qvo);
		return vo;
	}

	@Override
	public List<DickmShowVo> searchTreeList(DickmQueryVo vo) throws Exception {
		List<DickmShowVo> dataList = sqlSessionTemplate.selectList(MAPPER_NAMESPACE + ".searchTreeList", vo);
		return dataList;
	}

	@Override
	public List<DickmShowVo> ajaxTreeList(DickmQueryVo dickm) throws Exception {
		List<DickmShowVo> dataList = sqlSessionTemplate.selectList(MAPPER_NAMESPACE + ".ajaxTreeList", dickm);
		return dataList;
	}

	@Override
	public List<DickmShowVo> searchAllList(String leiBie) throws Exception {
		List<DickmShowVo> dataList = sqlSessionTemplate.selectList(MAPPER_NAMESPACE + ".searchAllList", leiBie);
		return dataList;
	}

	@Override
	public BusinessMap setChuShiYuE(ZhangTao zt, String currKeMuFenLei, List<DickmShowVo> pareList) throws Exception {
		BusinessMap bm = new BusinessMap();
		// 删除旧数据
		boolean isScuu = this.deleteInitialFinancialbalance(zt.getUuid(), currKeMuFenLei);
		if (isScuu) {
			// 添加初始余额
			bm = this.createInitialFinancialbalance(pareList);
		}
		return bm;
	}

	@Override
	public BusinessMap setChuShiYuE2(ZhangTao zt, String currKeMuFenLei, List<DickmShowVo> pareList) throws Exception {
		BusinessMap bm = new BusinessMap();
		// 删除旧数据
		boolean isScuu = this.deleteInitialFinancialbalance(zt.getUuid(), currKeMuFenLei);
		if (isScuu) {
			// 添加初始余额
			if (pareList.size() > 0) {
				bm = this.createInitialFinancialbalance(pareList);
			}
		}
		return bm;
	}

}
